/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int pseudoPalindromicPaths(TreeNode *root)
    {
        vector<int> digitCount(10, 0);
        int result = 0;
        auto verify = [&]()
        {
            int oddCount = 0;
            for (int count : digitCount)
            {
                if (count & 1)
                {
                    ++oddCount;
                }
            }
            return oddCount <= 1;
        };
        function<void(TreeNode *)> dfs = [&](TreeNode *node)
        {
            ++digitCount[node->val];
            if (node->left == nullptr && node->right == nullptr)
            {
                if (verify())
                {
                    ++result;
                }
            }
            else
            {
                if (node->left != nullptr)
                {
                    dfs(node->left);
                }
                if (node->right != nullptr)
                {
                    dfs(node->right);
                }
            }
            --digitCount[node->val];
        };
        dfs(root);
        return result;
    }
};